<template>
    <div class="general-menu">
        <!-- 菜单栏 -->
        <div id="aside-menu" class="flex flex-col items-center">
            <div id="current-user-avatar">
                <img :src="userStore().userInfo.avatar" alt="">
            </div>
            <!-- <div id="tool-bar-menu" class="flex flex-col items-center justify-evenly">
                <div id="bar-items" class="flex items-center justify-center"
                    v-for="(barItem, barItemIndex) in toolBarMenus" :key="barItemIndex"
                    @click="menuClick(barItem.url as string, barItem.key as string)">
                    <img :src="barItem.icon" :alt="barItem.label" :title="barItem.label">
                </div>
            </div> -->
            <n-menu :options="menuOptions" :render-icon="renderMenuIcon" @update:value="handleMenuClick" />
        </div>
    </div>

    <!-- 展示用户好友信息的dialog  showContactInfo -->
    <el-dialog class="contant-dialog" v-model="showContactInfo" :show-close="false" :width="ContactDialogWidth">
        <!-- 标题信息 -->
        <div id="detail-title">
            <h1>Recommend Friend Detail Info</h1>
        </div>
        <el-tabs v-model="currentActiveTab" :tab-position="tabPosition" @tab-click="handleTabClick" class="demo-tabs">
            <el-tab-pane label="请信" name="request">
                <div id="request-friend-info-list">
                    <div id="request-item"
                        v-for="(requestItem, requestItemIndex) in friend_store.storageFriendRequestList"
                        :key="requestItemIndex" v-show="friend_store.storageFriendRequestList.length > 0">
                        <!-- 申请人基本信息 -->
                        <div id="basic-info" class="flex flex-col items-center">
                            <span>申请人：{{ requestItem.username }}</span>
                            <span>申请语：{{ requestItem.message }}</span>
                        </div>
                        <!-- 操作按钮（上下排列） -->
                        <div id="control-btns" class="flex items-center justify-around">
                            <el-button plain @click="acceptFriendRequest(requestItem)">
                                <template #default>
                                    <el-icon size="23">
                                        <Check />
                                    </el-icon>
                                </template>
                            </el-button>
                            <el-button plain @click="refuseFriendRequest(requestItem.fromUserId)">
                                <template #default>
                                    <el-icon size="23">
                                        <Close />
                                    </el-icon>
                                </template>
                            </el-button>
                        </div>
                    </div>
                    <div id="request-item" v-show="friend_store.storageFriendRequestList.length <= 0">
                        <h1>暂无好友请求消息哦</h1>
                    </div>
                </div>
            </el-tab-pane>
            <el-tab-pane label="推荐" name="recommend">
                <el-scrollbar height="300px">
                    <div id="refer-friends">
                        <div id="refer-items" v-for="(referItem, referItemIndex) in friend_store.recommendFriends"
                            :key="referItemIndex" @click="onContextMenu($event, websocket as WebSocket, referItem)">
                            <div id="info">
                                <p>{{ referItem.username }}</p>
                                <p v-if="referItem.area">{{ referItem.area }}</p>
                                <p v-else>未知星球</p>
                            </div>
                        </div>
                    </div>
                </el-scrollbar>
            </el-tab-pane>
            <el-tab-pane label="群聊" name="group-chats">
                <el-scrollbar height="320px">
                    <el-transfer v-model="infoValue" filterable :titles="['好友列表', '群聊成员']" :button-texts="['回来', '出去']"
                        :data="transferData" :props="{
                            key: 'key',
                            label: 'label',
                            avatar: 'avatar'
                        }" @change="handleTranserClick">
                        <!-- 自定义空内容 -->
                        <template #left-empty>
                            <el-empty :image-size="60" description="No data" />
                        </template>
                        <template #right-empty>
                            <el-empty :image-size="60" description="No data" />
                        </template>
                    </el-transfer>
                    <!-- 显示创建群聊可以配置的信息 -->
                    <div class="chat-group-info flex flex-wrap items-center justify-evenly">
                        <!-- 群聊名称 -->
                        <div id="group-name">
                            <label for="name">
                                <span>群名：</span>
                            </label>
                            <el-input id="name" v-model="pullGroupInfo.group_name" placeholder="输入群名"
                                clearable></el-input>
                        </div>
                        <!-- 群聊类型 -->
                        <div id="group-type">
                            <label for="type">
                                <span>群类型：</span>
                            </label>
                            <el-tree-select v-model="pullGroupInfo.group_type" :data="groupTypes" :props="{
                                label: 'label',
                                value: 'url',
                                children: 'subTypes'
                            }" style="width: 200px;" clearable />
                        </div>
                        <!-- 最后的操作按钮 -->
                        <div id="operate-btns" class="flex items-center justify-around">
                            <el-button type="primary" plain @click="pullGroupChats('pull')">pull
                                group</el-button>
                            <el-button type="primary" plain @click="pullGroupChats('clear')">重置信息</el-button>
                        </div>
                    </div>
                </el-scrollbar>
            </el-tab-pane>
        </el-tabs>
    </el-dialog>

    <!-- 在这里显示推荐好友的详细信息           后期扩展丰富 -->
    <el-drawer class="detail-drawer" v-model="showDetailStatus" :show-close="true" title="Recommend Friend Detail Info"
        :with-header="false">
        <!-- <h1>here are about recommend friends's details info</h1> -->
        <!-- 用户信息 -->
        <div id="user-details-info">
            <!-- 展示用户自定义背景照片         这里加个条件判断（存在显示反之使用默认照片） -->
            <!-- <div class="background-photo">
                <img src="../../assets/R-C.jpg" alt="">
            </div> -->
            <div id="normal-info" class="flex items-center justify-evenly">
                <div id="avatar">
                    <img :src="currentDetailsInfo.avatar" alt="">
                </div>
                <div id="other-info">
                    <span id="name">{{ currentDetailsInfo.username }}</span>
                    <span id="gex">{{ currentDetailsInfo.gex }}</span>
                    <p id="uuId">{{ currentDetailsInfo.uu_id }}</p>
                </div>
            </div>
            <div id="basic-info">
                <div id="area-info" class="flex flex-row items-center justify-between text-center">
                    <label for="area">
                        <span>地区</span>
                    </label>
                    <p id="area" v-if="currentDetailsInfo.area != null">{{ currentDetailsInfo.area }}</p>
                    <p id="area" v-else>未知星球!</p>
                </div>
                <div id="friend-ships" class="flex flex-row items-center justify-around text-center">
                    <label for="ships">
                        <span>交签</span>
                    </label>
                    <!-- 在这里使用match结合正则表达式将string转换为Array -->
                    <div v-if="currentDetailsInfo.typeOfFriendShips != null" id="ships"
                        v-for="(shipItem, shipItemIndex) in JSON.parse(currentDetailsInfo.typeOfFriendShips).slice(0, 3)"
                        :key="shipItemIndex">
                        <!-- 只显示前三个标签内容 -->
                        <!-- match(/(\w+)/g) -->
                        <p>{{ shipItem }}</p>
                    </div>
                    <div id="other-items" v-else>
                        <p>用户还没有兴趣爱好哦!</p>
                    </div>
                </div>
                <div id="signatureOfTheIndividual" class="flex items-center justify-between">
                    <label for="signature">
                        <span>个签</span>
                    </label>
                    <p id="signature" v-if="currentDetailsInfo.signatureOfTheIndividual != '暂无'">{{
                        currentDetailsInfo.signatureOfTheIndividual }}</p>
                    <p id="signature" v-else>还没有设置个签哦!</p>
                </div>
                <!-- 操作按钮 -->
                <div id="operate-btns" class="flex items-center justify-evenly">
                    <el-button type="primary"
                        @click="addFriend(websocket as WebSocket, currentDetailsInfo)">加好友</el-button>
                    <el-button type="warning">biu一下</el-button>
                </div>
            </div>
        </div>
    </el-drawer>


</template>


<script setup lang="ts">
import { onMounted, PropType, ref, watch, watchEffect } from 'vue';
import { friendStore } from '@store/friendStore';
import {
    refuseFriendRequest, acceptFriendRequest, getRecommendFriends,
    callFactory
} from "@utils/axiosApi"
import type { Option, MembersInfo } from '../../types/types'
import { onContextMenu } from "@utils/contextMenu"
import { connectWebSocket } from "@utils/webSocketService"
import {
    showContactInfo, showToolBarMenu, handleTabClick, showDetailStatus, currentActiveTab, paginatedMenus, getRequestInfo,
    currentDetailsInfo, addFriend, pullGroupChats, groupTypes, pullGroupInfo, infoValue, toolBarMenus, menuOptions, renderMenuIcon,
} from '@/components/Menu/menu';
import { ElMessage, TabsInstance, TransferDirection, TransferKey } from 'element-plus';
import { userStore } from '@store/userStore';
import { useGlobalState } from '@store/globalState';

let websocket = ref<WebSocket | null>(connectWebSocket());

const friend_store = friendStore();

const useGlobal = useGlobalState();

const emits = defineEmits(["menu-click"]);

// tab标签定位
const tabPosition = ref<TabsInstance['tabPosition']>('top');


// 处理点击菜单事件
function handleMenuClick(url: string, key: string) {
    if (useGlobal.appMounted) {
        return key === '/contact' ? showContactInfo.value = true : emits('menu-click', url, key);
    } else {
        ElMessage.error("等待加载ing");
    }
}

// 动态设置contact dialog宽度的变量
const ContactDialogWidth = ref<number>(700);


const transferData = ref<Option[] | null>(null);


// 初始化transfer信息
const generateData = (): Option[] => {
    const data: Option[] = [];
    const friendList = friend_store.storageUserFriendList;
    if (friendList.length > 0) {
        for (let i = 0; i < friendList.length; i++) {
            // 获取好友信息
            const friend = friend_store.storageUserFriendList[i].friendDetails;
            if (friend && friend.username) {
                data.push({
                    // key: i,      避免使用props，这里的key直接使用uu_id
                    key: `${friend.uu_id}`,
                    label: `${friend.username}`,
                    avatar: `${friend.avatar}`
                    // disabled: i % 4 === 0
                })
            } else {
                ElMessage.warning(`用户信息不完整，索引为 ${i}`);
            }
        }
        return data;
    } else {
        ElMessage.warning('未知的数据！');
    }
    return [];
}


watchEffect(() => {
    if (friend_store.storageUserFriendList.length > 0) {
        // 初始化数据
        transferData.value = generateData();
    }
})

// const selectedTransferLabel = ref<string[]>([]);        // 存储当前选中的transfer元素
// 处理transfer点击的事件
const handleTranserClick = (value: TransferKey[], direction: TransferDirection, movedKeys: TransferKey[]) => {
    // 通过keys获取移动的label  两个办法
    // 1、默认返回一个数组需要使用扩展运算符处理
    const movedItem = movedKeys.map((key: any): any => {
        const item = transferData.value?.find((data: any) => data.key === key);
        return item ? item : null;
    })
    // 2、明确规定返回一个对象  直接push
    if (movedItem) {
        if (direction === 'right') {
            // 添加信息
            pullGroupInfo.group_members!.push(...movedItem)
        } else if (direction === 'left') {
            // 去除信息
            pullGroupInfo.group_members = pullGroupInfo.group_members!.filter((member: MembersInfo) => {
                return !movedKeys.includes(member.key);
            })
        }
    } else {
        ElMessage.warning("获取元素出现未知的错误！");
    }
}



onMounted(async (): Promise<void> => {
    getRequestInfo();
    getRecommendFriends();
    // getBelongsGroup();
})

</script>




<style scoped lang="scss">
@import url("./menu.scss");
</style>
